<script setup>
import { ref, onMounted, h } from 'vue'
import { Table, Tag, Avatar, Button, Space, Input, Modal, Form, Select, DatePicker, message } from 'ant-design-vue'
import { EditOutlined, DeleteOutlined, PlusOutlined, SearchOutlined, CheckCircleOutlined, CloseCircleOutlined } from '@ant-design/icons-vue'
import { userApi } from '@/api/user'

// 用户数据
const users = ref([])
const loading = ref(false)
const pagination = ref({
  current: 1,
  pageSize: 10,
  total: 0
})
const searchKeyword = ref('')

// 模态框状态
const isModalVisible = ref(false)
const isEditMode = ref(false)
const currentUser = ref({
  id: null,
  username: '',
  passwordHash: '',
  email: '',
  avatar: '',
  role: 'subscriber',
  status: 'ACTIVE',
  createdAt: null,
  updatedAt: null,
  lastLogin: null,
  isDeleted: false
})

// 角色映射
const roleMap = {
  ADMIN: '管理员',
  EDITOR: '编辑',
  SUBSCRIBER: '订阅者'
}

// 状态映射
const statusMap = {
  ACTIVE: { text: '启用', color: 'green' },
  INACTIVE: { text: '禁用', color: 'red' },
  ENABLED: { text: '启用', color: 'green' },
  DISABLED: { text: '禁用', color: 'red' }
}

// 软删除映射
const deleteMap = {
  false: { text: '未删除', color: 'blue' },
  true: { text: '已删除', color: 'red' }
}

// 当前筛选条件
const currentFilters = ref({});

// 获取单个用户
const fetchUserById = async (userId) => {
  
  // 更严格的userId有效性检查
  if (typeof userId === 'undefined' || userId === null || (typeof userId === 'string' && userId.trim() === '')) {
    console.error('fetchUserById: 用户ID无效或不存在:', userId);
    message.error('用户ID无效，请检查数据');
    return null;
  }
  
  try {
    // 直接调用API
    const response = await userApi.getUserById(userId);
    
    console.log('获取用户详情API调用成功，响应状态:', response?.status);
    console.log('API响应数据:', response?.data);
    
    // 检查响应数据
    if (response?.data && response.data.code === 200) {
      console.log('用户详情数据获取成功:', response.data.data);
      return response.data.data;
    } else {
      console.warn('API返回非成功状态:', response?.data?.code, response?.data?.message);
      message.error(response?.data?.message || '获取用户详情失败');
      return null;
    }
  } catch (error) {
    console.error('获取用户详情API调用失败:', error);
    console.error('错误详情:', error.response || error.message);
    message.error('获取用户详情失败，请检查网络连接或服务器状态');
    return null;
  }
}

// 创建用户
const createUser = async () => {
  try {
    const response = await userApi.createUser(currentUser.value)
    if (response.data.code === 200) {
      message.success('创建用户成功')
      isModalVisible.value = false
      fetchUsers(pagination.value.current, pagination.value.pageSize, searchKeyword.value, currentFilters.value)
    } else {
      message.error(response.data.message || '创建用户失败')
    }
  } catch (error) {
    console.error('创建用户失败:', error)
    message.error('创建用户失败')
  }
}

// 更新用户
const updateUser = async () => {
  // 检查currentUser是否存在且有效
  if (!currentUser.value || typeof currentUser.value.id === 'undefined' || currentUser.value.id === null) {
    console.error('updateUser: 用户数据无效或缺少ID:', currentUser.value);
    message.error('用户数据无效，无法更新');
    return;
  }
  
  try {
    // 调用API更新用户
    const response = await userApi.updateUser(currentUser.value);
    // 检查响应结果
    if (response?.data && response.data.code === 200) {
      console.log('用户更新成功，刷新用户列表');
      message.success('更新用户成功');
      // 关闭模态框
      isModalVisible.value = false;
      // 刷新用户列表
      fetchUsers(pagination.value.current, pagination.value.pageSize, searchKeyword.value, currentFilters.value);
    } else {
      message.error(response?.data?.message || '更新用户失败');
    }
  } catch (error) {
    // 显示更具体的错误信息
    if (error.response) {
      message.error(`更新失败: ${error.response.status} - ${error.response.data?.message || '未知错误'}`);
    } else {
      message.error('更新用户失败，请检查网络连接或服务器状态');
    }
  }
}

// 删除用户
const deleteUser = async (userId) => {
  try {
    const response = await userApi.deleteUser(userId)
    if (response.data.code === 200) {
      message.success('删除用户成功')
      fetchUsers(pagination.value.current, pagination.value.pageSize, searchKeyword.value, currentFilters.value)
    } else {
      message.error(response.data.message || '删除用户失败')
    }
  } catch (error) {
    console.error('删除用户失败:', error)
    message.error('删除用户失败')
  }
}

// 批量更新用户状态
const batchUpdateStatus = async (userIds, status) => {
  try {
    const response = await userApi.batchUpdateStatus(userIds, status)
    if (response.data.code === 200) {
      message.success('批量更新状态成功')
      fetchUsers(pagination.value.current, pagination.value.pageSize, searchKeyword.value, currentFilters.value)
    } else {
      message.error(response.data.message || '批量更新状态失败')
    }
  } catch (error) {
    console.error('批量更新状态失败:', error)
    message.error('批量更新状态失败')
  }
}

// 打开添加用户模态框
const showAddModal = () => {
  isEditMode.value = false
  currentUser.value = {
    id: null,
    username: '',
    passwordHash: '',
    email: '',
    avatar: '',
    role: 'SUBSCRIBER',
    status: 'ACTIVE',
    createdAt: null,
    updatedAt: null,
    lastLogin: null,
    isDeleted: false
  }
  isModalVisible.value = true
}

// 打开编辑用户模态框
const showEditModal = async (record) => {
  // 简化参数检查，使用typeof来确保更准确的判断
  if (!record || typeof record.id === 'undefined' || record.id === null) {
    console.error('showEditModal: 记录或ID无效:', record);
    message.error('无法编辑: 无效的用户数据');
    isEditMode.value = false;
    return;
  }
  
  // 设置编辑模式
  isEditMode.value = true;
  
  try {
    // 直接使用record.id调用API
    const userDetail = await fetchUserById(record.id);
    
    if (userDetail) {
      // 直接赋值用户详情
      currentUser.value = { ...userDetail };
      // 显示模态框
      isModalVisible.value = true;
    } else {
      isEditMode.value = false;
      message.error('未找到用户数据');
    }
  } catch (error) {
    isEditMode.value = false;
    message.error('打开编辑对话框失败，请稍后重试');
  }
}

// 搜索处理
const handleSearch = () => {
  fetchUsers(1, pagination.value.pageSize, searchKeyword.value, currentFilters.value)
}

// 表格选中的行
const selectedRowKeys = ref([])
const selectedRows = ref([])

// 行选择配置
const rowSelection = {
  selectedRowKeys,
  onChange: (newSelectedRowKeys, newSelectedRows) => {
    selectedRowKeys.value = newSelectedRowKeys
    selectedRows.value = newSelectedRows
  }
}

// 批量状态更新模态框
const isBatchStatusModalVisible = ref(false)
const batchTargetStatus = ref('')

const showBatchStatusModal = (status) => {
  batchTargetStatus.value = status
  isBatchStatusModalVisible.value = true
}

const handleBatchStatusConfirm = () => {
  if (selectedRowKeys.value.length > 0) {
    batchUpdateStatus(selectedRowKeys.value, batchTargetStatus.value)
    isBatchStatusModalVisible.value = false
    selectedRowKeys.value = []
  }
}

const handleBatchStatusCancel = () => {
  isBatchStatusModalVisible.value = false
}

// 处理分页变化
const handlePageChange = (pageNum, pageSize) => {
  fetchUsers(pageNum, pageSize, searchKeyword.value, currentFilters.value)
}

// 表格列配置

// 表格列配置
const columns = [
  {
    title: '选择',
    type: 'selection',
    key: 'selection'
  },
  {
    title: 'ID',
    dataIndex: 'id',
    key: 'id',
    width: 80
  },
  {
    title: '用户名',
    dataIndex: 'username',
    key: 'username'
  },
  {
    title: '邮箱',
    dataIndex: 'email',
    key: 'email'
  },
  {
    title: '头像',
    dataIndex: 'avatar',
    key: 'avatar',
    width: 80,
    customRender: ({ text: avatar }) => {
      return h(Avatar, { src: avatar || 'https://via.placeholder.com/40' })
    }
  },
  {
    title: '角色',
    dataIndex: 'role',
    key: 'role',
    filters: [
      { text: '管理员', value: 'ADMIN' },
      { text: '编辑', value: 'EDITOR' },
      { text: '订阅者', value: 'SUBSCRIBER' }
    ],
    customRender: ({ text: role }) => {
      const color = role === 'ADMIN' ? 'red' : role === 'EDITOR' ? 'blue' : 'green'
      return h(Tag, { color }, roleMap[role] || role)
    }
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    filters: [
      { text: '启用', value: 'ACTIVE' },
      { text: '禁用', value: 'INACTIVE' }
    ],
    customRender: ({ text: status }) => {
      return h(Tag, { color: statusMap[status]?.color || 'gray' }, statusMap[status]?.text || status)
    }
  },
  {
    title: '创建时间',
    dataIndex: 'createdAt',
    key: 'createdAt'
  },
  {
    title: '更新时间',
    dataIndex: 'updatedAt',
    key: 'updatedAt'
  },
  {
    title: '最后登录',
    dataIndex: 'lastLogin',
    key: 'lastLogin'
  },
  {
    title: '软删除',
    dataIndex: 'isDeleted',
    key: 'isDeleted',
    filters: [
      { text: '未删除', value: false },
      { text: '已删除', value: true }
    ],
    customRender: ({ text: deleted }) => {
      return h(Tag, { color: deleteMap[deleted]?.color || 'gray' }, deleteMap[deleted]?.text || deleted)
    }
  },
  {
    title: '操作',
    key: 'action',
    fixed: 'right',
    width: 120,
    customRender: ({ record }) => {
        // 使用正确的customRender参数结构
        const handleEdit = () => {
          // 检查record和record.id
          if (!record || typeof record.id === 'undefined') {
            console.error('编辑按钮点击错误: 记录或ID不存在', record);
            message.error('无法编辑: 记录信息无效');
            return;
          }
          
          // 调用showEditModal，传递正确的record参数
          showEditModal(record);
        };
        
        const handleDelete = () => {
          if (!record || typeof record.id === 'undefined') {
            console.error('删除按钮点击错误: 记录或ID不存在', record);
            message.error('无法删除: 记录信息无效');
            return;
          }
          deleteUser(record.id);
        };
        
        return h(Space, { size: 'middle' }, [
          h(Button, { 
            type: 'text', 
            icon: h(EditOutlined), 
            onClick: handleEdit,
            'data-user-id': record?.id || 'undefined'
          }, '编辑'),
          h(Button, { 
            type: 'text', 
            danger: true, 
            icon: h(DeleteOutlined), 
            onClick: handleDelete,
            'data-user-id': record?.id || 'undefined'
          }, '删除')
        ]);
      }
  }
]

// 初始化数据
onMounted(() => {
  fetchUsers(1, pagination.value.pageSize, '', currentFilters.value)
})

// 处理表格过滤
const handleTableChange = (page, filters, sorter) => {
  // 合并当前分页信息
  const currentPage = page.current || pagination.value.current;
  const pageSize = page.pageSize || pagination.value.pageSize;
  
  // 保存当前筛选条件
  currentFilters.value = filters;
  
  // 根据筛选条件重新获取数据
  fetchUsers(currentPage, pageSize, searchKeyword.value, filters);
};

// 获取用户列表（支持筛选）
const fetchUsers = async (pageNum = 1, pageSize = 10, keyword = '', filters = {}) => {
  loading.value = true
  try {
    // 先调用原始API获取所有数据
    const response = await userApi.getUsers(pageNum, pageSize, keyword)
    let filteredData = response.data.data.records
    
    // 客户端实现筛选逻辑
    if (filters.role && filters.role.length > 0) {
      filteredData = filteredData.filter(user => filters.role.includes(user.role))
    }
    if (filters.status && filters.status.length > 0) {
      filteredData = filteredData.filter(user => filters.status.includes(user.status))
    }
    if (filters.isDeleted && filters.isDeleted.length > 0) {
      filteredData = filteredData.filter(user => filters.isDeleted.includes(user.isDeleted))
    }
    
    // 更新显示数据
    users.value = filteredData
    pagination.value.total = filteredData.length
    pagination.value.current = pageNum
    pagination.value.pageSize = pageSize
  } catch (error) {
    console.error('获取用户列表失败:', error)
    message.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

// 处理表单提交
const handleSubmit = () => {
  if (isEditMode.value) {
    updateUser()
  } else {
    createUser()
  }
}
</script>

<template>
  <div class="user-container">
    <div style="display: flex; justify-content: space-between; margin-bottom: 24px; align-items: center;">
      <h1 style="margin: 0;">用户管理</h1>
      <div style="display: flex; gap: 16px; align-items: center;">
        <Space>
          <Button type="primary" :icon="h(CheckCircleOutlined)" @click="showBatchStatusModal(1)" :disabled="selectedRowKeys.length === 0">
            启用所选
          </Button>
          <Button type="primary" danger :icon="h(CloseCircleOutlined)" @click="showBatchStatusModal(0)" :disabled="selectedRowKeys.length === 0">
            禁用所选
          </Button>
        </Space>
        <Space>
          <Input
            v-model:value="searchKeyword"
            placeholder="搜索用户名或邮箱"
            :prefix="h(SearchOutlined)"
            style="width: 250px;"
            @keyup.enter="handleSearch"
          />
          <Button type="primary" @click="handleSearch">搜索</Button>
        </Space>
        <Button type="primary" :icon="h(PlusOutlined)" @click="showAddModal">添加用户</Button>
      </div>
    </div>
    
    <Table
      :columns="columns"
      :data-source="users"
      row-key="id"
      :scroll="{ x: 1400 }"
      @change="handleTableChange"
      :loading="loading"
      :pagination="{
        showSizeChanger: true,
        showQuickJumper: true,
        total: pagination.total,
        current: pagination.current,
        pageSize: pagination.pageSize,
        onChange: handlePageChange
      }"
      :row-selection="rowSelection"
    />
    
    <!-- 用户表单模态框 - 美化版 -->
    <Modal
      v-model:open="isModalVisible"
      :title="isEditMode ? '编辑用户' : '添加用户'"
      @ok="handleSubmit"
      @cancel="isModalVisible = false"
      width="650px"
      :body-style="{ padding: '24px', backgroundColor: '#fafafa' }"
      :header-style="{ backgroundColor: '#f0f5ff', borderBottom: 'none', borderRadius: '8px 8px 0 0', color: '#409eff' }"
      :footer-style="{ borderTop: 'none', backgroundColor: '#fafafa', padding: '16px 24px 24px' }"
      style="border-radius: 12px; overflow: hidden; box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);"
    >
      <Form layout="vertical" class="user-form">
        <Form.Item 
          label="用户名" 
          required
          :label-col="{ style: { fontWeight: 'bold', color: '#606266', marginBottom: '8px' } }"
        >
          <Input 
            v-model:value="currentUser.username" 
            placeholder="请输入用户名" 
            class="form-input"
            :style="{ borderRadius: '8px', borderColor: '#dcdfe6', transition: 'all 0.3s' }"
          />
        </Form.Item>
        <Form.Item 
          label="密码" 
          v-if="!isEditMode" 
          required
          :label-col="{ style: { fontWeight: 'bold', color: '#606266', marginBottom: '8px' } }"
        >
          <Input.Password 
            v-model:value="currentUser.passwordHash" 
            placeholder="请输入密码" 
            class="form-input"
            :style="{ borderRadius: '8px', borderColor: '#dcdfe6', transition: 'all 0.3s' }"
          />
        </Form.Item>
        <Form.Item 
          label="邮箱" 
          required
          :label-col="{ style: { fontWeight: 'bold', color: '#606266', marginBottom: '8px' } }"
        >
          <Input 
            v-model:value="currentUser.email" 
            placeholder="请输入邮箱" 
            class="form-input"
            :style="{ borderRadius: '8px', borderColor: '#dcdfe6', transition: 'all 0.3s' }"
          />
        </Form.Item>
        <Form.Item 
          label="头像"
          :label-col="{ style: { fontWeight: 'bold', color: '#606266', marginBottom: '8px' } }"
        >
          <div style="display: flex; gap: 12px; align-items: flex-end;">
            <Input 
              v-model:value="currentUser.avatar" 
              placeholder="请输入头像URL" 
              class="form-input"
              :style="{ flex: 1, borderRadius: '8px', borderColor: '#dcdfe6', transition: 'all 0.3s' }"
            />
            <div 
              v-if="currentUser.avatar" 
              style="width: 60px; height: 60px; border-radius: 8px; overflow: hidden; border: 2px solid #e4e7ed; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);"
            >
              <img 
                :src="currentUser.avatar" 
                alt="头像预览" 
                style="width: 100%; height: 100%; object-fit: cover;"
              />
            </div>
          </div>
        </Form.Item>
        <Form.Item 
          label="角色" 
          required
          :label-col="{ style: { fontWeight: 'bold', color: '#606266', marginBottom: '8px' } }"
        >
          <Select 
            v-model:value="currentUser.role" 
            class="form-select"
            :style="{ width: '100%', borderRadius: '8px', borderColor: '#dcdfe6', transition: 'all 0.3s' }"
          >
            <Select.Option value="ADMIN" style="color: #f56c6c;">管理员</Select.Option>
            <Select.Option value="EDITOR" style="color: #e6a23c;">编辑</Select.Option>
            <Select.Option value="SUBSCRIBER" style="color: #67c23a;">订阅者</Select.Option>
          </Select>
        </Form.Item>
        <Form.Item 
          label="状态" 
          required
          :label-col="{ style: { fontWeight: 'bold', color: '#606266', marginBottom: '8px' } }"
        >
          <Select 
            v-model:value="currentUser.status" 
            class="form-select"
            :style="{ width: '100%', borderRadius: '8px', borderColor: '#dcdfe6', transition: 'all 0.3s' }"
          >
            <Select.Option value="1" style="color: #67c23a;">启用</Select.Option>
            <Select.Option value="0" style="color: #909399;">禁用</Select.Option>
          </Select>
        </Form.Item>
      </Form>
    </Modal>

    <!-- 批量状态更新模态框 -->
    <Modal
      v-model:open="isBatchStatusModalVisible"
      title="批量更新状态"
      @ok="handleBatchStatusConfirm"
      @cancel="handleBatchStatusCancel">
      <p>确定要将选中的 {{ selectedRowKeys.length }} 个用户状态更新为{{ batchTargetStatus === 1 ? '启用' : '禁用' }}吗？</p>
    </Modal>
  </div>
</template>

<style scoped>
.user-container {
  padding: 20px;
}

.user-form {
  animation: fadeIn 0.3s ease-in-out;
}

.user-form :deep(.ant-form-item) {
  margin-bottom: 20px;
}

.user-form :deep(.ant-input:focus),
.user-form :deep(.ant-select-focused .ant-select-selector) {
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
  border-color: #409eff;
}

.user-form :deep(.ant-input:hover),
.user-form :deep(.ant-select-selector:hover) {
  border-color: #409eff;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}
</style>
